import React from 'react';
import {Row,Col,Input,Button,Icon,Table,Modal,Popover} from 'antd';
import './home.less';
import config from './config/config';
import getFormatData from './common/getFormatData';
import $ from 'jquery';
import {browserHistory} from 'react-router';
const allRouter = config.router;
let token = sessionStorage.getItem('token');
class Home extends React.Component {
    constructor(props){
        super(props);
        this.state={
            Inkey: '',// 关键字
            currentdate:'',//中间显示的一周的日期区间
            dateStart:'',//用于传递时间区间起始
            dateEnd:'',//用于传递时间区间结尾
            month:[],//月份，用于表头显示
            strDate:[],//日期，用于表头显用
            clickCount:0,//记录上一周或下一周点击次数
            nowDate:new Date(),//获得现在日期函数
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            schedulingsList:[],//班次列表
            today:'',
            clickCount1:0,//记录上一天或下一天点击次数
            datalist:[],
            scheduleListData:[],//排班列表(左下角 )
            totallist:{},
            timearr:["",""],
            datalist1:[],//所有接诊情况列表
        }

    }
    componentWillMount() {
        // console.log(this.props.location.state);
        this.iniDate(this.state.nowDate);
        this.getshop();
        this.initSingleDate(new Date().getTime());
    }
    componentDidMount() {
    }
    //日期函数(周计)
    iniDate(now){
        //获取指定的日期和时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数。
        let nowTime = now.getTime() ;
        //获取星期及几
        let day = now.getDay();
        //一天的毫秒数
        let oneDayLong = 24*60*60*1000 ;
        console.log(day);
        let MondayTime;
        let SundayTime;
        if(day==0){
            //获取本周所在周一
            MondayTime = nowTime - (day-1+7)*oneDayLong ;
            //获取本周所在周末
            SundayTime = nowTime + (7-day-7)*oneDayLong ;
        }else{
            //获取本周所在周一
            MondayTime = nowTime - (day-1)*oneDayLong ;
            //获取本周所在周末
            SundayTime = nowTime + (7-day)*oneDayLong ;
        }
        //转化日期  星期一的日期和星期天的日期
        let monday = new Date(MondayTime);
        let sunday = new Date(SundayTime);
        //星期一的月份
        let month = monday.getMonth() + 1;
        //星期一的日期
        let strDate = monday.getDate();
        //星期天的月份
        let month1 = sunday.getMonth() + 1;
        //星期天的日期
        let strDate1 = sunday.getDate();
        let currentdate = monday.getFullYear() + "年" + month + "月" + strDate +"日"+ "-" + sunday.getFullYear() + "年" + month1 + "月" + strDate1+"日";
        let dateStart= (monday.getFullYear()+'-'+(month<10?'0':'')+month+'-'+(strDate<10?'0':'')+strDate);
        let dateEnd= (sunday.getFullYear()+'-'+(month1<10?'0':'')+month1+'-'+(strDate1<10?'0':'')+strDate1);
        let monthTotalItem=this.state.month;
        let strDateItem=this.state.strDate;
        for(let i=0;i<7;i++){
            monthTotalItem.push(new Date(MondayTime+(i)*oneDayLong).getMonth() + 1);
            strDateItem.push(new Date(MondayTime+(i)*oneDayLong).getDate());
        }
        // console.log(currentdate);
        // console.log(monthTotalItem);
        // console.log(strDateItem);
        this.setState({
            currentdate,
            month:monthTotalItem,
            strDate:strDateItem,
            dateStart:dateStart,
            dateEnd:dateEnd,
        },()=>{
            console.log(this.state.currentdate);
            console.log(this.state.dateStart);
            console.log(this.state.dateEnd);
            this.getDoctorScheduleList(this.state.dateStart,this.state.dateEnd);
        })
    }
    //日期函数(天计)
    initSingleDate(now){
        //获取指定的日期和时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数。
        let today = new Date(now);
        let month = today.getMonth() + 1;
        let strDate = today.getDate();
        let dateStart= (today.getFullYear()+'-'+(month<10?'0':'')+month+'-'+(strDate<10?'0':'')+strDate);
        this.setState({
           today:dateStart,
        },()=>{
            console.log(this.state.today);
            this.getList(dateStart)
        })
    }
    //上一天点击事件
    lastDayBtn(){
        let clickCount1=this.state.clickCount1;
        clickCount1--;
        this.setState({
            clickCount1,
        },()=>{
            let date = new Date(new Date().getTime() + clickCount1*24*3600*1000);
            this.initSingleDate(date);
        });
    }
    //下一天点击事件
    nextDayBtn(){
        let clickCount1=this.state.clickCount1;
        clickCount1++;
        this.setState({
            clickCount1,
        },()=>{
            let date = new Date(new Date().getTime() + clickCount1*24*3600*1000);
            this.initSingleDate(date);
        });
    }
    //回到本天点击事件
    thisDayBtn(){
        this.setState({
            clickCount1:0
        },()=>{
            let date = new Date(new Date().getTime());
            this.initSingleDate(date);
        });

    }
    //上一周点击事件
    lastWeekBtn(){
        let clickCount=this.state.clickCount;
        clickCount--;
        this.setState({
            clickCount,
            month:[],
            strDate:[]
        },()=>{
            let date = new Date(new Date().getTime() + clickCount*7*24*3600*1000);
            this.iniDate(date);
        });

    }
    //下一周点击事件
    nextWeekBtn(){
        let clickCount=this.state.clickCount;
        clickCount++;
        this.setState({
            clickCount,
            month:[],
            strDate:[]
        },()=>{
            let date = new Date(new Date().getTime() + clickCount*7*24*3600*1000);
            this.iniDate(date);
        });

    }
    //回到本周点击事件
    thisWeekBtn(){
        this.setState({
            month:[],
            strDate:[],
            clickCount:0
        },()=>{
            let date = new Date(new Date().getTime());
            this.iniDate(date);
        });

    }
    //搜索关键字
    changeInkey(e) {
        this.setState({
            Inkey: e.target.value
        })
    }
    //搜索
    searchPatient(e) {
        let value = e.target.value || this.state.Inkey;
        console.log(value);
        if(!value){
            return;
        }
        this.getPatientInfo(1,value);

    }
    //获取患者登记信息
    getPatientInfo(pageindex, value) {
        let url = allRouter.patientOrigin + '/patient/list';
        if(this.props.location.state){
            token=this.props.location.state;
        }
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+token},
            data: {
                pageindex,
                pagesize: 12,
                searchtext: value,
            },
            success: data => {
                console.log(data);
                if(data.code===200){
                    if(data.counts===0){
                        const modal = Modal.error({
                            title: '操作失败',
                            content: '无搜索结果',
                        });
                        setTimeout(() => modal.destroy(),3000);
                    }else{
                        browserHistory.push({pathname:'registerTriage',state:value});
                    }
                }else{
                    console.log(data.mes);
                }
            },
            error: err => {
                console.log(err);
            }
        });
    }
    //获取排班信息列表
    getDoctorScheduleList(time1,time2){
        let url=allRouter.patientOrigin+'/home/findarrange';
        if(this.props.location.state){
            token=this.props.location.state;
        }
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+token},
            data:{
                starttime:time1,
                endtime:time2
            },
            success:data=>{
                console.log("医生排班列表:");
                console.log(data);
                let today=new Date();
                if(data.code===200){
                    let scheduleListData=[];
                    for(let i=0;i<7;i++){
                        let day=today.getFullYear()+'/'+this.state.month[i]+'/'+this.state.strDate[i];
                        let day1=new Date(today.getFullYear()+'/'+(today.getMonth()+1)+'/'+today.getDate()).getTime();
                        scheduleListData.push({date:i,data:{status:day1>new Date(day).getTime(),fore:[],after:[]}});
                        if(data.forenoon){
                            data.forenoon.map((item)=>{
                                if(item[day]){
                                    scheduleListData[i].data.fore.push(item[day]);
                                }
                            })
                        }
                        if(data.afternoon){
                            data.afternoon.map((item)=>{
                                if(item[day]){
                                    scheduleListData[i].data.after.push(item[day]);
                                }
                            })
                        }
                    }
                    this.setState({
                        scheduleListData
                    },()=>{
                        console.log(scheduleListData);
                    })
                }else{
                    console.log("获取医生排班列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }
    //门店信息
    getshop(){
        let url=allRouter.patientOrigin+'/cmmuseum/one/'+JSON.parse(sessionStorage.getItem('UserInfo')).shop[0];
        if(this.props.location.state){
            token=this.props.location.state;
        }
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+token},
            success:data=>{
                console.log(data);
                this.setState({
                    timearr:data.cmmuseum?[data.cmmuseum.starttime,data.cmmuseum.endtime]:['08:00:00','18:00:00']
                });

            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //今日就诊信息
    getList(date){
        let url=allRouter.patientOrigin+'/home/findpatient';
        if(this.props.location.state){
            token=this.props.location.state;
        }
        $.ajax({
            url:url,
            type: "get",
            headers: { Authorization: 'Bearer '+token},
            data:{
                day:date
            },
            async: true,
            success:(d)=> {
                console.log(d);
                let datalist=[];
                var newtime=this.state.timearr[0].split(':');
                newtime=newtime[0]+':'+newtime[1];
                //newtime='08:30';
                datalist[0]={time:newtime,name:[]}
                for(var n=1;n<100;n++){
                    if((parseInt(datalist[n-1].time.split(':')[1])+30)>60){
                        if(parseInt(datalist[n-1].time.split(':')[0])<9){
                            if((parseInt(datalist[n-1].time.split(':')[1])+30-60)>=10){
                                datalist[n]={time:'0'+(parseInt(datalist[n-1].time.split(':')[0])+1)+':'+(parseInt(datalist[n-1].time.split(':')[1])+30-60),name:[]}
                            }else{
                                datalist[n]={time:'0'+(parseInt(datalist[n-1].time.split(':')[0])+1)+':0'+(parseInt(datalist[n-1].time.split(':')[1])+30-60),name:[]}

                            }
                        }else{
                            datalist[n]={time:(parseInt(datalist[n-1].time.split(':')[0])+1)+':00',name:[]}
                        }
                    }
                    else if((parseInt(datalist[n-1].time.split(':')[1])+30)==60){
                        if(parseInt(datalist[n-1].time.split(':')[0])<9){
                            datalist[n]={time:'0'+(parseInt(datalist[n-1].time.split(':')[0])+1)+':00',name:[]}
                        }else{
                            datalist[n]={time:(parseInt(datalist[n-1].time.split(':')[0])+1)+':00',name:[]}
                        }
                    }else{
                        if(parseInt(datalist[n-1].time.split(':')[0])<10){
                            datalist[n]={time:'0'+parseInt(datalist[n-1].time.split(':')[0])+':'+(parseInt(datalist[n-1].time.split(':')[1])+30),name:[]}
                        }else{
                            datalist[n]={time:parseInt(datalist[n-1].time.split(':')[0])+':'+(parseInt(datalist[n-1].time.split(':')[1])+30),name:[]}

                        }
                    }
                    if(datalist[n].time==this.state.timearr[1].split(':')[0]+':'+this.state.timearr[1].split(':')[1]){
                        break;
                    }
                }
                console.log(datalist);
                var amp=0;
                var apmp=0;
                for(let m=0;m<datalist.length;m++){
                    for(let n=0;n<d.data.length;n++){
                        if(d.data[n].receptiontime.split(' ')[1]==datalist[m].time){
                            datalist[m].name.push({'name':d.data[n].payer_name,'state':d.data[n].receptionstate,'dept':d.data[n].department.department_name})
                        }

                    }
                }
                for(var y=0;y<datalist.length;y++){
                    apmp+=datalist[y].name.length;
                }
                for(var k=0;k<datalist.length;k++){
                    if(datalist[k].time=='12:30'){
                        break;
                    }
                    amp+=datalist[k].name.length;
                }

                var totallist={sum:d.sum,outpatient:d.outpatient,awaits:d.awaits,complate:d.complate,done:d.done,amp:amp,pmp:apmp-amp};
                console.log(datalist)
                this.setState({
                    datalist:datalist,
                    datalist1:datalist,
                    totallist:totallist
                });

            }
        });
    }
    //待接诊点击事件
    handleWaitForTraige(i){
        console.log(this.state.datalist1);
        let arr=[];
        arr = JSON.parse(JSON.stringify(this.state.datalist1));
        if(i===0){
            this.setState({
                datalist:arr,
            });
            return;
        }
        let arr1=[];
        arr.forEach(item=>{
            if(item.name.length>0){
                let arr2=[];
                item.name.forEach(key=>{
                    console.log(key);
                    if(key.state===i){
                        arr2.push(key);
                    }
                });
                item.name=arr2;
            }
            arr1.push(item);
        });
        this.setState({
            datalist:arr1,
        })
    }
    render(){
        const{month,strDate}=this.state;
        //排班就诊
        const columns = [
            {
                title: '日期',
                dataIndex:'date',
                width: 130,
                render:(text)=>{return <div style={{fontSize:'16px'}}>
                    <span>{text===0?'周一':text===1?'周二':text===2?'周三':text===3?'周四':text===4?'周五':text===5?'周六':text===6?'周日':''}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span>{month[text]+"月"+strDate[text]+'日'}</span>
                </div>
                    }
            }, {
                title: '排班信息',
                dataIndex: 'data',
                width: 120,
                render: text => {
                    return <div className="index-no-hover">
                        <Popover content= {<div>{text.fore.map((item,i)=><p key={i}>{item}</p>)}</div>}>
                            <Button  style={{background:text.status?'#999':'#43b1a5',color:'#fff'}}>上午{text.fore.length}名医生</Button>
                        </Popover>
                        <Popover content= {<div>{text.after.map((item,i)=><p key={i}>{item}</p>)}</div>}>
                            <Button style={{background:text.status?'#999':'#43b1a5',color:'#fff'}}>下午{text.after.length}名医生</Button>
                        </Popover>
                    </div>
                }
            }
        ];
        return <div className="container">
            <div className="index-box" >
                <Row>
                    <Col span={8}>
                        <div className="index-search">
                            <Row>
                                <Col span={20}>
                                    <Input size="large"
                                        placeholder="请输入姓名或手机号"
                                        value={this.state.Inkey}
                                        onChange={(e) => this.changeInkey(e)}
                                        onPressEnter={(e)=>this.searchPatient(e)}
                                    />
                                </Col>
                                <Col span={4}>
                                    <Button type="primary" size="large" className='member-button' icon="search" onClick={this.searchPatient.bind(this)}>搜索</Button>
                                </Col>
                            </Row>
                        </div>
                        <div className="todays-triage">
                            <Row  align="middle">
                                <Col span={4} offset={4} style={{paddingTop:'26px'}}>
                                    <img src={require('../images/jinrijiuzhen.png')}/>
                                </Col>
                                <Col span={10} offset={1} style={{  color: '#fff' }}>
                                    <div style={{textAlign:'center'}}>
                                        <span style={{fontWeight:'bold',fontSize:'16px'}}>今日就诊概况</span>
                                            <Row style={{marginTop:'20px'}}>
                                                <Col span={12} style={{borderRight:'1px solid #ddd'}}>
                                                    <h3 style={{  color: '#fff' }}>总人数：</h3>
                                                    <p ><b>{this.state.totallist.sum}</b>人</p>
                                                </Col>
                                                <Col span={12}>
                                                    <h3 style={{  color: '#fff' }}>门诊人数：</h3>
                                                    <p><b>{this.state.totallist.outpatient}</b>人</p>
                                                </Col>
                                            </Row>
                                    </div>
                                </Col>
                            </Row>
                        </div>
                        <div className="schedule-triage" style={{marginTop:'40px'}}>
                            <h2>排班就诊</h2>
                            <div className="my-clear-fix"  style={{marginBottom:'20px'}}>
                                <Button  onClick={this.lastWeekBtn.bind(this)}><Icon type="left" />上一周</Button>
                                <Button　onClick={this.nextWeekBtn.bind(this)}>下一周<Icon type="right" /></Button>
                                <Button type="primary" style={{float:'right'}} onClick={this.thisWeekBtn.bind(this)}>回到本周</Button>
                            </div>
                            <div className='all-roles-table'>
                                <Table
                                    rowKey="date"
                                    columns={columns}
                                    dataSource={this.state.scheduleListData}
                                    pagination={false}
                                    bordered
                                />
                            </div>
                        </div>
                    </Col>
                    <Col span={15} offset={1}>
                        <Row>
                            <Col span={3} >
                                <h2>今日就诊</h2>
                            </Col>
                            <Col span={10} offset={1} >
                                <span className="all-triage-patient" onClick={this.handleWaitForTraige.bind(this,0)}>全部</span>
                                <span className="all-triage-patient" onClick={this.handleWaitForTraige.bind(this,2)}><i className="index-icon-style" style={{background:'#DE6262'}}></i>待接诊{this.state.totallist.awaits}人</span>
                                <span className="all-triage-patient" onClick={this.handleWaitForTraige.bind(this,3)}><i className="index-icon-style" style={{background:'#0099CC'}}></i>接诊中{this.state.totallist.complate}人</span>
                                <span className="all-triage-patient" onClick={this.handleWaitForTraige.bind(this,4)}><i className="index-icon-style" style={{background:'#43B1A5'}}></i>已完成{this.state.totallist.done}人</span>
                            </Col>
                            <Col span={9} offset={1}>
                                <div className="my-clear-fix"  style={{marginBottom:'20px'}}>
                                    <Button  onClick={this.lastDayBtn.bind(this)}><Icon type="left" />上一天</Button>
                                    <Button　onClick={this.nextDayBtn.bind(this)}>下一天<Icon type="right" /></Button>
                                    <Button type="primary" style={{float:'right'}} onClick={this.thisDayBtn.bind(this)}>今天</Button>
                                </div>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24} className='shijian'>
                                <table className="cc_table">
                                    <thead>
                                    <tr>
                                        <th width="100">时间</th>
                                        <th width="700">
                                            <div style={{display:'flex',justifyContent:'space-between'}}>
                                                <span>{this.state.today}</span><span>上午：{this.state.totallist.amp}人</span> <span >下午：{this.state.totallist.pmp}人</span> <Button  onClick={()=>(browserHistory.push('registerTriage'))} type='primary' size="small"><Icon type="plus" />新增患者</Button>
                                            </div>
                                        </th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    { this.state.datalist.length>0?
                                        this.state.datalist.map((item,i)=>{
                                            return <tr key={i}>
                                                <td>{item.time}</td>
                                                <td>
                                                    {
                                                        item.name.length>0?
                                                        item.name.map((item2,i)=>{
                                                            return <Button key={i} size="small" style={{'background':['#DE6262','#DE6262','#DE6262','#0099CC','#43B1A5'][item2.state],color:'#fff'}}>{item2.name}({item2.dept})</Button>
                                                        }):''
                                                    }
                                                </td>
                                            </tr>
                                        }):<tr><td colSpan="2">请先设置排班信息</td></tr>
                                    }
                                    </tbody>
                                </table>
                            </Col>
                        </Row>
                    </Col>
                </Row>
            </div>
        </div>
    }
}


export default Home;